package com.example.smartretaildemo.module.shoppingcart.fragment;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CompoundButton;
import android.widget.Toast;

import com.example.smartretaildemo.bean.shoppingcart.ShopCartInfo;
import com.example.smartretaildemo.databinding.FragmentShoppingCartBinding;
import com.example.smartretaildemo.module.shoppingcart.activity.QRcodeActivity;
import com.example.smartretaildemo.module.shoppingcart.adapter.ShopCartRViewAdapter;
import com.example.smartretaildemo.network.sqliteopenhelper.MyDataAdapter;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link ShoppingCartFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class ShoppingCartFragment extends Fragment {

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
    private FragmentShoppingCartBinding binding;
    private List<ShopCartInfo> cartList;    //从数据库读取购物车数据
    private List<ShopCartInfo> payList = new ArrayList<>();     //向结算界面传递的数组
    ShopCartRViewAdapter mAdapter;
    LinearLayoutManager mManager;
    private double priceCount;  //总价

    public ShoppingCartFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment ShoppingCartFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static ShoppingCartFragment newInstance(String param1, String param2) {
        ShoppingCartFragment fragment = new ShoppingCartFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        binding = FragmentShoppingCartBinding.inflate(inflater, container, false);
        // Inflate the layout for this fragment
        setList();
//        RecycleView具体控件点击事件
        mAdapter = new ShopCartRViewAdapter(getContext(), cartList) {
            @Override
            public void onBindViewHolder(@NonNull ShopCartRViewAdapter.ViewHolder holder, int position) {
                super.onBindViewHolder(holder, position);
                ViewHolder v = (ViewHolder) holder;
//                增加数量
                v.tvShopAdd.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        int num = Integer.parseInt(v.tvShopNum.getText().toString()) + 1;
                        if (num > 99) {
                            Toast.makeText(getContext(), "商品数量不能大于99", Toast.LENGTH_SHORT).show();
                        } else {
                            v.tvShopNum.setText(String.valueOf(num));
                            v.cheBoxShop.setChecked(false);
                        }
                    }
                });
//                减少数量
                v.tvShopSub.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        int num = Integer.parseInt(v.tvShopNum.getText().toString()) - 1;
                        if (num < 1) {
                            Toast.makeText(getContext(), "商品数量不能小于1", Toast.LENGTH_SHORT).show();
                        } else {
                            v.tvShopNum.setText(String.valueOf(num));
                            v.cheBoxShop.setChecked(false);
                        }
                    }
                });
//                单选控件更新监听
                v.cheBoxShop.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                        String sPrice = v.tvShopPrice.getText().toString().substring(4);
                        String sNum = v.tvShopNum.getText().toString();
                        double price = Double.parseDouble(sPrice);
                        int num = Integer.parseInt(sNum);
                        double count = price * num;
                        if (b) {
//                            为结束列表添加数据
                            payList.add(new ShopCartInfo(cartList.get(position).getCommodityId(), cartList.get(position).getCommodityName(), cartList.get(position).getfCostPrice(), cartList.get(position).getNum(), cartList.get(position).getPic()));
//                            总价更改
                            priceCount += count;
                        } else {
//                            移除所添加的数据
                            for(int i=0;i<payList.size();i++){
                                if(payList.get(i).getCommodityId() == cartList.get(position).getCommodityId())
                                    payList.remove(i);
                            }

//                            总价更改
                            priceCount -= count;
                        }
                        if (priceCount < 0) {
//                            总价最小为0
                            priceCount = 0;
                        }
//                        设置为小数点后两位
                        binding.tvShopPriceAll.setText("合计：￥" + String.format("%1.2f", priceCount));
                    }
                });
                v.btnShopDel.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
//                        这是一个删除所有相同的，若删除单个则需另设随机不重复Id
                        new MyDataAdapter().delete(getContext(), cartList.get(position).getCommodityId());
                        cartList.remove(position);
                        setList();
                        mAdapter.notifyDataSetChanged();
                    }
                });
            }
        };
        binding.rvShopList.setAdapter(mAdapter);
//        结束按钮跳转二维码界面
        binding.btnShopSettlement.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getContext(), QRcodeActivity.class);
//                传递序列化后的结算列表
                intent.putExtra("payList", (Serializable) payList);
//                传递总价
                intent.putExtra("priceCount", String.format("%1.2f", priceCount));
                startActivity(intent);
                getActivity().finish();
            }
        });
        return binding.getRoot();
    }

//    根据数据库所存储的数据数量设置控件
    private void setList() {
        cartList = new MyDataAdapter().QueryAll(getContext());
        if (cartList.size() != 0) {
            binding.tvShopCartEmpty.setVisibility(View.GONE);
            binding.rvShopList.setVisibility(View.VISIBLE);
            binding.LineLayoutShopPrice.setVisibility(View.VISIBLE);
        } else {
            binding.tvShopCartEmpty.setVisibility(View.VISIBLE);
            binding.rvShopList.setVisibility(View.GONE);
            binding.LineLayoutShopPrice.setVisibility(View.GONE);
        }
        mManager = new LinearLayoutManager(getContext());
        binding.rvShopList.setLayoutManager(mManager);
    }
}